App = {
  web3Provider: null,
  contracts: {},

  init: async function() {
    // Load pets.
    $.getJSON('../pets.json', function(data) {
      var petsRow = $('#petsRow');
      var petTemplate = $('#petTemplate');

      for (i = 0; i < data.length; i ++) {
        petTemplate.find('.panel-title').text(data[i].name);
        petTemplate.find('img').attr('src', data[i].picture);
        petTemplate.find('.pet-breed').text(data[i].breed);
        petTemplate.find('.pet-age').text(data[i].age);
        petTemplate.find('.pet-location').text(data[i].location);
        petTemplate.find('.btn-adopt').attr('data-id', data[i].id);

        petsRow.append(petTemplate.html());
      }
    });

    return await App.initWeb3();
  },
  // 初始化web3
  initWeb3: async function() {
    /* 新版的方式 */
  if (window.ethereum) {
    App.web3Provider = window.ethereum;
    try {
      // 请求用户授权
      await window.ethereum.enable();
    } catch (error) {
      // 用户不授权时
      console.error("User denied account access")
    }
  } else if (web3) {
    App.web3Provider = web3.currentProvider;
  } else {
    App.web3Provider = new Web3.providers.HttpProvider('http://192.168.1.240:7545');
  }

    web3 = new Web3(App.web3Provider);

    return App.initContract();
  },
  // 初始化合约
  initContract: function() {
    $.getJSON('Adoption.json', function(data) {
      var AdoptionArtifact = data;

      App.contracts.Adoption = TruffleContract(AdoptionArtifact);

      App.contracts.Adoption.setProvider(App.web3Provider);

      return App.markAdopted();
    });

    return App.bindEvents();
  },
  // 领养事件
  bindEvents: function() {
    $(document).on('click', '.btn-adopt', App.handleAdopt);
  },
  // 标记当前的宠物是否已经被领养
  markAdopted: function() {
    var adoptionInstance;
    //拿到合约的实例
    App.contracts.Adoption.deployed().then(function(instace) {
      adoptionInstance = instace;
      //调取所有的领养者信息，合同的getAdopters方法调用
      return adoptionInstance.getAdopters();
    }).then(function(adopters) {
        for(i = 0; i < adopters.length; i++) {
            if(adopters[i] != '0x0000000000000000000000000000000000000000'){
              $('.panel-pet').eq(i).find('button').text('Success').attr('disabled', true);
            }
        }
    }).catch(function(err){
      console.log(err.message);
    });
  },
  //领养
  handleAdopt: function(event) {
    event.preventDefault();

    var petId = parseInt($(event.target).data('id'));
    var adoptionInstance;
    web3.eth.getAccounts(function(error, accounts){
      var account = accounts[0];
      App.contracts.Adoption.deployed().then(function(instace) {
        adoptionInstance = instace;
        return adoptionInstance.adopt(petId, {from: account});
      }).then(function(result){
        return App.markAdopted();
      }).catch(function(err){
        console.log(err.message);
      });
    });
  }

};

$(function() {
  $(window).load(function() {
    App.init();
  });
});
